import axios from 'axios'
import router from '@/router'
import { MessageBox, Message } from 'element-ui'
import md5 from 'js-md5'
import { login } from '@/api/system'
let istime = Date.parse(new Date()) - 5000
// 设置请求的地址
// axios.defaults.baseURL = "http://1.117.168.204:9989"; // 打包地址（线上）
// axios.defaults.baseURL = 'http://60.163.198.70:9989' // 打包地址（客户服务器）
// axios.defaults.baseURL = "http://192.168.1.65:9989"; // 打包地址（本地）
// axios.defaults.baseURL = 'http://192.168.177.6:9989' // 打包地址
axios.defaults.baseURL = 'https://zhny.bbyiot.com/intelligent_agriculture_webservice' // 打包地址
// axios.defaults.baseURL = 'http://192.168.0.109:8080/' // 打包地址
console.log(456)

// 请求超时时间
axios.defaults.timeout = 5000000000000000000000000000000000000000000000000000000000
// 允许跨域
axios.defaults.withCredentials = true
// 设置默认的Content-Type
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8'
function decode(str) {
  return decodeURIComponent(
    atob(str)
      .split('')
      .map(function (c) {
        return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2)
      })
      .join('')
  )
}
// axios请求拦截器，可以统一给所有axios请求加上相同的参数，也可以统一新增token_1
axios.interceptors.request.use(
  config => {
    let token_1 = window.localStorage.getItem('token_1')

    if (token_1) {
      config.headers['Authorization'] = token_1
    }

    if (config.data && config.method == 'post') {
      axios.defaults.headers.post['Content-Type'] = 'application/json'
    }

    return config
  },
  error => {
    return Promise.error(error)
  }
)
let status = true
const get = (url, params) => {
  return new Promise((resolve, reject) => {
    axios
      .get(`${url}`, { params: params })
      .then(res => {
        if (res.data.code === 200) {
          //成功
          status = true
          resolve(res.data)
        } else if (res.data.code === 421 && status == true) {
          //未登录
          status = false
          let nowtime = Date.parse(new Date())
          if (nowtime - istime > 5000) {
            if (router.currentRoute.query && router.currentRoute.query.user) {
              let username = decode(router.currentRoute.query.user)
              let password = decode(router.currentRoute.query.psd)
              password = md5(md5(password) + 'bby')
              login({
                password: password,
                username: username
              }).then(res => {
                window.localStorage.setItem('token_1', res.data.token_1)
                window.localStorage.setItem('roleId', res.data.roleId)
                location.reload()
              })
            } else {
              router.push({ path: `/?redirect=${router.currentRoute.path}` })
              MessageBox.confirm('登录已过期，需要重新登录', {
                confirmButtonText: '重新登录',
                type: 'warning'
              }).then(() => {
                router.push({ path: `/?redirect=${router.currentRoute.path}` })
              })
            }
            istime = Date.parse(new Date())
          }
        } else {
          Message.error(res.data.msg)
        }
      })
      .catch(error => {
        reject(error.data)
      })
  })
}

const post = (url, params) => {
  return new Promise((resolve, reject) => {
    axios
      .post(`${url}`, params)
      .then(res => {
        if (res.data.code === 200) {
          //成功
          resolve(res.data)
        } else if (res.data.code === 421) {
          //未登录
          MessageBox.confirm(`${res.data.msg}，可以取消继续留在该页面，或者重新登录`, '重新登录', {
            confirmButtonText: '重新登录',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            router.push({ path: `/?redirect=${router.currentRoute.path}` })
          })
        } else {
          Message.error(res.data.msg)
        }
      })
      .catch(error => {
        reject(error.data)
      })
  })
}
const fpost = (url, params) => {
  axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded; charset=utf-8'
  return new Promise((resolve, reject) => {
    axios
      .post(`${url}`, params)
      .then(res => {
        if (res.data.code === 200) {
          //成功
          resolve(res.data)
        } else if (res.data.code === 421) {
          //未登录
          MessageBox.confirm(`${res.data.msg}，可以取消继续留在该页面，或者重新登录`, '重新登录', {
            confirmButtonText: '重新登录',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            router.push({ path: `/?redirect=${router.currentRoute.path}` })
          })
        } else {
          Message.error(res.data.msg)
        }
      })
      .catch(error => {
        reject(error.data)
      })
  })
}
const del = (url, params) => {
  return new Promise((resolve, reject) => {
    axios
      .delete(`${url}`, { params: params })
      .then(res => {
        if (res.data.code === 200) {
          //成功
          resolve(res.data)
        } else if (res.data.code === 421) {
          //未登录
          MessageBox.confirm(`${res.data.msg}，可以取消继续留在该页面，或者重新登录`, '重新登录', {
            confirmButtonText: '重新登录',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            router.push({ path: `/?redirect=${router.currentRoute.path}` })
          })
        } else {
          Message.error(res.data.msg)
        }
      })
      .catch(error => {
        reject(error.data)
      })
  })
}

export { get, post, del, fpost }
